package se.jayway.millionaire.client;

import java.util.Random;

import se.jayway.millionaire.model.game.Answer;
import se.jayway.millionaire.model.game.GameRoundFinishedException;
import se.jayway.millionaire.model.game.Player;
import se.jayway.millionaire.model.game.PlayerChoice;

/**
 * A dummy player that randomly choose an answer after a random amount of time.
 * 
 * @author magnus
 */
public class RandomPlayer implements Player {

	private final String name;
	private final Random rand = new Random();
	
	public RandomPlayer(String name) {
		this.name = name;
	}
	
	public void onNewGameRound(final PlayerChoice playerChoice) {
		Thread thread = new Thread(new Runnable() {
			public void run() {
				hesitateSomeTime();
				try {
					makeChoice(playerChoice);
				} catch (GameRoundFinishedException e) {
					System.out.println(name + ": Ooops, too late...");
				}
			}

			private void makeChoice(final PlayerChoice playerChoice) {
				int answerIndex = rand.nextInt(4) + 1;
				System.out.println(name + ": Guessing number " + answerIndex);
				Answer[] answerAlternatives = playerChoice.getGameRound().getQuestion().getAnswerAlternatives();
				playerChoice.setPlayerAnswer(answerAlternatives[answerIndex - 1]);
			}

			private void hesitateSomeTime() {
				try {
					Thread.sleep(1000 + rand.nextInt(3000));
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
		thread.start();
	}

	public void onFinishedGameRound(final PlayerChoice playerChoice, final Answer correctAnswer) {
		StringBuilder buf = new StringBuilder();
		if (playerChoice.getPlayerAnswer() == correctAnswer) {
			buf.append(name + ": CORRECT!");
		} else {
			buf.append(name + ": WRONG...");
		}
		buf.append(" [Correct:");
		buf.append(playerChoice.getGameSession().countCorrectAnswers());
		buf.append(", In a row:");
		buf.append(playerChoice.getGameSession().countCorrectAnswersInRow());
		buf.append(", Wrong:");
		buf.append(playerChoice.getGameSession().countWrongAnswers());
		buf.append(", Missed:");
		buf.append(playerChoice.getGameSession().countNoAnswers());
		buf.append("]");
		System.out.println(buf);
	}
	
	public void onWin(PlayerChoice playerChoice) {
		System.out.println(name + ": I WON, I WON, I WON!!!");
	}
	
	public String toString() {
		return name;
	}
}
